"""User model definition for AncientSeeker.

Implements both registered and guest users.
"""

from __future__ import annotations

from datetime import datetime
from typing import Optional

from sqlalchemy import String, Boolean, DateTime, func, Column, Integer
from sqlalchemy.orm import Mapped, mapped_column, declarative_base
from app.database import Base


class User(Base):
    """Represents an application user (registered or guest)."""

    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    username: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    email: Mapped[Optional[str]] = mapped_column(
        String(256), unique=True, nullable=True
    )
    password_hash: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
    avatar_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    is_admin: Mapped[bool] = mapped_column(Boolean, default=False)
    is_guest: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    last_active_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )

    def mark_active(self):
        self.last_active_at = datetime.utcnow()

    def __repr__(self) -> str:  # pragma: no cover - repr convenience
        role = "guest" if self.is_guest else "user"
        return f"<User id={self.id} username={self.username} role={role}>"
